<template>
  <div class="transportation-manage">
    <TopBar />
    <div class="content">
      <MenuLine />
      <div class="operation-bar">
        <el-button type="primary" :icon="Plus" @click="openAddDialog">添加运输记录</el-button>
      </div>
      <el-table :data="transportationList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="vehicleLicensePlate" label="车牌号" min-width="150" />
        <el-table-column prop="destination" label="目的地" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="250" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteTransportation(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="450px"
        @close="resetForm"
        :close-on-click-modal="false"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item label="选择车辆" prop="vehicleId">
            <el-select
              v-model="form.vehicleId"
              placeholder="请选择运输车辆"
              style="width: 100%"
              filterable
              clearable
              :loading="loadingVehicles"
              @visible-change="handleVehicleSelectFocus"
            >
              <el-option
                v-for="option in vehicleOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
                :disabled="option.disabled"
              />
              <el-option v-if="!vehicleOptions.length && !loadingVehicles" disabled label="无可用车辆" :value="null" />
            </el-select>
          </el-form-item>
          <el-form-item label="目的地" prop="destination">
            <el-input
              v-model="form.destination"
              placeholder="请输入目的地"
              :maxlength="100"
              clearable
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { useTransportationStore, type Transportation, type TransportationPayload, type VehicleOption } from '@/stores/transportation';
import type { Vehicle } from '@/stores/vehicle';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// Store
const transportationStore = useTransportationStore();

// 本地 State
const transportationList = ref<Transportation[]>([]);
const vehicleOptions = ref<VehicleOption[]>([]);
const loading = ref(false);
const loadingVehicles = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('添加运输记录');
const isEdit = ref(false);
const submitLoading = ref(false);
const form = ref<TransportationPayload>({
  vehicleId: null,
  destination: '',
});
const formRef = ref<FormInstance>();

// Form validation rules
const rules = ref<FormRules>({
  vehicleId: [
    { required: true, message: '请选择运输车辆', trigger: 'change' },
  ],
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' },
    { min: 1, max: 100, message: '目的地长度在 1 到 100 字符', trigger: 'blur' },
  ],
});

// 获取运输记录列表
const fetchTransportations = async () => {
  loading.value = true;
  try {
    transportationList.value = await transportationStore.fetchTransportations();
  } catch (error) {
    transportationList.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取车辆并处理成选项
const fetchVehicles = async () => {
  if (loadingVehicles.value) return;
  loadingVehicles.value = true;
  try {
    const vehiclesData: Vehicle[] = await transportationStore.fetchVehiclesForSelect();
    vehicleOptions.value = vehiclesData.map((v: Vehicle) => ({
      value: v.id,
      label: `${v.licensePlate || '未知车牌'} (${v.brand || ''} ${v.model || ''}) - ${v.status}`,
      disabled: v.status !== '可用',
    }));
    console.log('Component: Updated vehicle options:', vehicleOptions.value);
  } catch (error) {
    vehicleOptions.value = [];
    console.error('Component: Failed to fetch vehicles:', error);
  } finally {
    loadingVehicles.value = false;
  }
};

// 处理车辆选择框打开事件
const handleVehicleSelectFocus = async (visible: boolean) => {
  if (visible && !loadingVehicles.value) {
    await fetchVehicles();
  }
};

// 打开添加弹窗
const openAddDialog = async () => {
  isEdit.value = false;
  dialogTitle.value = '添加运输记录';
  resetForm();
  await fetchVehicles();
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = async (row: Transportation) => {
  isEdit.value = true;
  dialogTitle.value = '编辑运输记录';
  await fetchVehicles();
  form.value = {
    id: row.id,
    vehicleId: row.vehicleId,
    destination: row.destination,
  };
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (isEdit.value) {
          await transportationStore.updateTransportation(form.value);
          ElMessage.success('编辑运输记录成功');
        } else {
          await transportationStore.createTransportation({
            vehicleId: form.value.vehicleId,
            destination: form.value.destination,
          });
          ElMessage.success('添加运输记录成功');
        }
        dialogVisible.value = false;
        await Promise.all([fetchTransportations(), fetchVehicles()]);
      } catch (error) {
        console.error('提交运输记录错误:', error);
      } finally {
        submitLoading.value = false;
      }
    } else {
      ElMessage.error('请检查表单输入项');
    }
  });
};

// 删除运输记录
const handleDeleteTransportation = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除该运输记录吗？关联车辆将变为空闲。', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await transportationStore.deleteTransportation(id);
    ElMessage.success('删除运输记录成功');
    await Promise.all([fetchTransportations(), fetchVehicles()]);
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除运输记录错误:', error);
    } else {
      ElMessage.info('取消删除');
    }
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = { vehicleId: null, destination: '' };
};

// 初始化加载
onMounted(async () => {
  await Promise.all([fetchVehicles(), fetchTransportations()]);
});
</script>

<style scoped>
.transportation-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
  display: flex;
  justify-content: flex-start;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
}
</style>